<template>
    <el-card class="card f fv">
        <div class="f fac fpj">
            <div class="title">种植管理</div>
            <div class="operation">
                <el-button type="primary" @click="openDialog(null, '添加')">添加作物</el-button>
            </div>
        </div>
        <!-- 搜索条件 -->
        <el-form style="margin-top: 0.12rem;" :model="data.searchform" :inline="true">
            <el-form-item label="作物名称">
                <el-input clearable style="width: 2rem;" @clear="getList(true)" v-model="data.searchform.name"
                    placeholder="请输入农作物名称" />
            </el-form-item>
            <el-form-item label="作物种类">
                <el-select style="width: 2rem;" clearable @change="getList(true)" v-model="data.searchform.category"
                    placeholder="请选择农作物种类">
                    <el-option v-for="item in data.plantCategory" :key="item" :label="item" :value="item" />
                </el-select>
            </el-form-item>
            <el-form-item label="种植农场">
                <el-select style="width: 2rem;" clearable @change="getList(true)" v-model="data.searchform.type"
                    placeholder="请选择农场">
                    <el-option v-for="item in data.landList" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="状态">
                <el-select style="width: 2rem;" clearable @change="getList(true)" v-model="data.searchform.yield"
                    placeholder="请选择农作物状态">
                    <el-option label="种植中" :value="0" />
                    <el-option label="已收获" :value="1" />
                </el-select>
            </el-form-item>
            <el-form-item label="">
                <el-button type="primary" @click="getList(true)">搜索</el-button>
            </el-form-item>
        </el-form>

        <!-- 表格 -->
        <el-table :data="data.tableList" :height="data.tableHeight" v-loading="data.tableLoading" stripe class="table">
            <el-table-column prop="name" align="center" label="名称" />
            <el-table-column prop="category" align="center" label="种类" />
            <el-table-column prop="land_id" align="center" label="农场">
                <template #default="scope">
                    {{ data.landList.filter(item => item.id == scope.row.land_id)[0]?.name }}
                </template>
            </el-table-column>
            <el-table-column prop="life_cycle" align="center" label="生长周期">
                <template #default="scope">
                    <span v-if="scope.row.yield != 0">已收获</span>
                    <span v-else>
                        {{ plantLifeCycle(scope.row) === '' ? '' : JSON.parse(scope.row.life_cycle)[plantLifeCycle(scope.row)].step }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column prop="area" align="center" label="种植面积" />
            <el-table-column prop="create_time" align="center" label="种植时间">
                <template #default="scope">
                    <span>{{ scope.row.create_time && utils.formatDate(new Date(scope.row.create_time).getTime(), 'Y-M-D H:I:S') }}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="操作">
                <template #default="scope">
                    <el-button @click="checkPlant(scope.row)">查看</el-button>
                    <el-button v-if="plantLifeCycle(scope.row) == JSON.parse(scope.row.life_cycle).length - 1 && scope.row.yield == 0" type="primary" @click="yieldPlant(scope.row)">收获</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination background style="margin-top: 0.16rem;" layout="->, total, sizes, prev, pager, next" :pager-count="5"
            v-model:current-page="data.pageNum" v-model:page-size="data.pageSize" :total="data.total"
            @size-change="getList()" @current-change="getList()" />

        <!-- 抽屉/弹框 -->
        <el-drawer v-model="dialogData.dialogVisible" :title="dialogData.dialogTitle" direction="rtl" @close="closeDialog">
            <div class="content">
                <el-form :model="dialogData.form" label-postion="left" label-width="0.8rem" :rules="dialogData.formRules" hide-required-asterisk ref="refForm">
                    <el-form-item label="作物名称" prop="name">
                        <el-input v-model="dialogData.form.name" placeholder="请输入作物名称" />
                    </el-form-item>
                    <el-form-item label="作物种类" prop="category">
                        <el-select v-model="dialogData.form.category" placeholder="请选择农作物种类">
                            <el-option v-for="item in data.plantCategory" :key="item" :label="item" :value="item" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="农场" prop="land_id">
                        <el-select v-model="dialogData.form.land_id" placeholder="请选择农场">
                            <el-option v-for="item in data.landList" :key="item.id" :label="item.name" :value="item.id" />
                        </el-select>
                        <span style="margin-left: 0.1rem;" v-if="dialogData.form.land_id">
                            可种植面积:<span style="color: red;">{{ dialogData.plantArea }}</span>㎡
                        </span>
                    </el-form-item>
                    <el-form-item label="种植面积" prop="area">
                        <el-input v-model.number="dialogData.form.area" placeholder="请输入种植面积">
                            <template #append>㎡</template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="生长周期" prop="lifeCycle">
                        <el-table :data="dialogData.lifeCycle" border style="width: 100%">
                            <el-table-column prop="step" align="center" label="生长阶段">
                                <template #default="scope">
                                    <el-input 
                                        v-if="scope.row.inputVisible" 
                                        v-model="scope.row.step" 
                                        style="width: 0.8rem"
                                        ref="saveTagInputStep" size="small"></el-input>
                                    <span v-else>{{ scope.row.step }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="day" align="center" label="所需天数">
                                <template #default="scope">
                                    <el-input 
                                        v-if="scope.row.inputVisible" 
                                        v-model="scope.row.day" 
                                        style="width: 0.8rem; margin-right: 0.1rem;"
                                        ref="saveTagInputDay" size="small"></el-input>
                                    <span v-else>{{ scope.row.day }}</span>天
                                </template>
                            </el-table-column>
                            <el-table-column prop="" label="操作">
                                <template #default="scope">
                                    <el-button v-if="scope.row.inputVisible" @click="saveLifeCycle(scope.row)" plain type="primary" size="small">保存</el-button>
                                    <el-button v-else size="small" @click="scope.row.inputVisible = true" plain type="primary">编辑</el-button>
                                    <el-button size="small" plain type="danger" @click="deleteLifeCycleStep(scope.row)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <div style="width: 100%; margin-top: 0.16rem;" class="f fac fpc">
                            <el-button type="primary" @click="addLifeCycle">添加阶段</el-button>
                        </div>

                    </el-form-item>
                </el-form>
                <div class="footer">
                    <el-button type="primary" @click="submit">确定</el-button>
                    <el-button @click="closeDialog">取消</el-button>
                </div>
            </div>
        </el-drawer>

        <el-dialog v-model="dialogData.plantDetailShow" width="4rem" :close-on-click-modal="false" :title="dialogData.plantDetailName">
            <el-steps align-center :active="dialogData.activeStep" direction="vertical" :space="120">
                <el-step v-for="item in dialogData.plantStep" :key="item.step" :title="item.step">
                    <template v-slot:description>
                        <el-descriptions column="1">
                            <el-descriptions-item label="所需天数">{{ item.day }}天</el-descriptions-item>
                            <el-descriptions-item :label="'预计' + item.step + '时间:'">{{ item.time }}</el-descriptions-item>
                        </el-descriptions>
                    </template>
                </el-step>
            </el-steps>
            <div class="yield" v-if="dialogData.plantYield != 0">
                <span>收获</span>
                <span class="name">{{ dialogData.plantDetailName }}</span>:
                <span class="yieldNum">{{ dialogData.plantYield }}</span>
            </div>
        </el-dialog>
    </el-card>
</template>

<script setup>
import { ref, onMounted, reactive, watch, watchEffect } from 'vue'
import http from '@/api/home'
import utils from '@/utils/utils'

const refForm = ref()

// 自定义校验规则
const validateArea = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入面积'))
  } else if (value > dialogData.plantArea) {
    callback(new Error('该农场种植面积不足'))
  } else {
    callback()
  }
}

// 数据集
const data = reactive({
    // 搜索表单对象
    searchform: {},
    // 表格数据
    tableList: [],
    // 表格高度
    tableHeight: 0,
    // 表格加载
    tableLoading: false,
    // 分页 
    pageNum: 1,
    pageSize: 20,
    total: 0,
    // 农场列表
    landList: [],
    // 作物种类
    plantCategory: ["粮食作物", "经济作物", "蔬菜作物", "果类", "饲料作物"]
})

// 弹框
const dialogData = reactive({
    // 是否显示
    dialogVisible: false,
    // 标题
    dialogTitle: '',
    // 表单数据 
    form: {},
    // 校验规则
    formRules: {
        name: [{ required: true, message: '请输入农作物名称', trigger: 'blur' }],
        category: [{ required: true, message: '请选择作物种类', trigger: 'change' }],
        land_id: [{ required: true, message: '请选择农场', trigger: 'change' }],
        area: [{ required: true, validator: validateArea, trigger: 'blur' }],
        // lifeCycle: [{ required: true, message: '请选择设置生长周期', trigger: 'change' }],
    },
    // 可种植面积
    plantArea: '',
    // 种植详情
    plantDetailShow: false,
    plantDetailName: '',
    plantStep: [],
    activeStep: 1,
    plantYield: 0
})

onMounted(() => {
    getLandList()
    getList()
})

// 获取农场列表
const getLandList = () => {
    http.landList({
        pageNum: 1,
        pageSize: 10000,
        type: 1
    }).then(res => {
        data.landList = res.data.records
    })
}

// 获取列表
const getList = (reset = false) => {
    if (reset) data.pageNum = 1
    data.tableLoading = true
    http.plantList({
        ...data.searchform,
        pageNum: data.pageNum,
        pageSize: data.pageSize
    }).then(res => {
        data.tableLoading = false
        data.tableList = res.data.records
        data.total = res.data.total
    }).finally(() => {
        data.tableLoading = false
    })
}

// 当前种植生长周期
const plantLifeCycle = (row) => {
    // 种植时间
    let plantTime = Math.round(new Date(row.create_time).getTime() / 1000)
    let curTime = Math.round(new Date() / 1000)
    let life_cycle = JSON.parse(row.life_cycle)
    // 相差时间
    let reduceTime = curTime - plantTime
    let result = ''
    if (life_cycle.length > 0) {
        life_cycle.forEach((item, index) => {
            // 各生长周期的时间
            let groupTime = item.day * 24 * 60 * 60
            if (reduceTime >= groupTime) {
                result = index
            }
        })
    }
    return result
}

// 打开对话框
const openDialog = (row, title) => {
    dialogData.dialogVisible = true
    if (row) {
        dialogData.form = { ...row }
    } else {
        dialogData.form = {}
        dialogData.lifeCycle = []
    }
    dialogData.dialogTitle = title
}

// 关闭对话框
const closeDialog = () => {
    dialogData.dialogVisible = false;
    refForm.value.resetFields();
    dialogData.form = {}
}

// 添加生长周期
const addLifeCycle = () => {
    if (!dialogData.lifeCycle) {
        dialogData.lifeCycle = []
    }
    dialogData.lifeCycle.push({
        step: '',
        day: '',
        inputVisible: true,
    })
}

// 保存生长周期
const saveLifeCycle = (row) => {
    // 不能为空
    if (row.day == '' || row.day == undefined || row.step == '' || row.step == undefined) return
    // 不能重复设置生长周期
    if (dialogData.lifeCycle.filter(item => item.step == row.step).length > 1) return
    row.inputVisible = false
}

// 删除生长周期（有问题，待处理TODO）
const deleteLifeCycleStep = (row) => {
    let index = dialogData.lifeCycle.findIndex(item => item.step == row.step)
    dialogData.lifeCycle.splice(index, 1)
}

//提交
const submit = () => {
    refForm.value.validate((valid) => {
        if (valid) {
            dialogData.form.lifeCycle = JSON.stringify(dialogData.lifeCycle)
            if (dialogData.dialogTitle == '添加') {
                http.plantAdd(dialogData.form).then(res => {
                    ElMessage({ type: 'success', message: res.message })
                    dialogData.dialogVisible = false
                    getList()
                })
            } else {
                
            }
        }
    })
}

// 收获
const yieldPlant = (row) => {
    ElMessageBox.prompt(`请输入收获${row.name}的数量`, '收获', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /.+/,
        inputErrorMessage: '请输入正确的数值',
    }).then(({ value }) => {
        http.yieldPlant({
            id: row.id,
            yield: value
        }).then(res => {
            ElMessage({type: 'success', message: res.message})
            getList()
        })
    })
    
}

// 查看
const checkPlant = (row) => {
    dialogData.plantDetailName = row.name
    dialogData.plantStep = JSON.parse(row.life_cycle).map(item => {
        let plantTime = Math.round(new Date(row.create_time).getTime() / 1000)
        let dayTime = item.day * 24 * 60 * 60
        let groupTime = plantTime + dayTime
        return {
            step: item.step,
            day: item.day,
            time: utils.formatDate(groupTime, 'Y-M-D HH:mm:ss')
        }
    })
    dialogData.activeStep = plantLifeCycle(row) + 1
    dialogData.plantYield = row.yield
    dialogData.plantDetailShow = true
}

watch(() => dialogData.form.land_id, (newValue, oldValue) => {
    if (newValue) {
        // 选择的农场
        let land = data.landList.filter(item => item.id == dialogData.form.land_id)[0]
        if (!land) {
            dialogData.plantArea = ''
            return
        }
        // 农场面积
        let landArea = land.area
        // 农场可种植面积
        let plantArea = landArea
        data.tableList.forEach(item => {
            if (item.yield == 0) {
                if (item.land_id == land.id) {
                    plantArea -= item.area
                }
            }
        });
        dialogData.plantArea = plantArea
    }
}, { deep: true })

// 设置表格高度
const setTableHeight = () => {
    let tableH = 320 // 距离下方的距离 
    let tableHeightDetail = window.innerHeight - tableH
    if (tableHeightDetail <= 400) {
        data.tableHeight = 400
    } else {
        data.tableHeight = window.innerHeight - tableH
    }
}
watchEffect(() => setTableHeight())

</script>

<style lang="scss" scoped>
.card {
    box-shadow: 0px 1px 4px 0px rgba(0, 0, 0, 0.2);
    margin-top: 0.14rem;
    height: calc(100vh - 0.68rem - 0.7rem);

    .title {
        font-size: 0.2rem;
        font-weight: bold;
        color: #000;
        padding-bottom: 0.1rem;
        border-bottom: 4px solid $ncpColor;
    }

    .role-input {
        width: 2rem;
        margin-right: 0.2rem;
    }

    .table {
        width: 100%;

        .table-sale {
            color: $helpColor;
        }

        .table-info {
            color: #9CA3AF;
            font-size: 0.12rem;
        }
    }

    .table-edit {
        color: $otherColor;
        margin-right: 0.2rem;
        cursor: pointer;

        &:hover {
            text-decoration: underline;
        }
    }

    .disabled {
        pointer-events: none;
        opacity: 0.8;
    }

    .table-delete {
        color: $helpColor;
        cursor: pointer;

        &:hover {
            text-decoration: underline;
        }
    }

    :deep(.el-drawer__title) {
        font-size: 0.16rem;
    }

    .content {
        position: relative;
        height: 100%;
        .map {
            width: 100%;
            height: 5.6rem;
        }

        .footer {
            position: absolute;
            bottom: 0;
            left: 0;
        }
    }
    .yield {
        .name {
            font-size: 0.16rem;
            color: $ncpColor;
            margin-right: 0.1rem;
        }
        .yieldNum {
            font-size: 0.2rem;
            color: $ncpColor;
        }
    }

}</style>